package com.meicloud.license.appl.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.meicloud.license.appl.vo.LicenseDto;
import com.meicloud.license.appl.vo.LicenseRegisterDto;
import com.meicloud.license.appl.vo.LicenseServer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * License工具
 *
 * @author zhanghui145
 * @date 2022/1/10 15:28
 * @since 1.0.0
 */
@Component
public class LicenseClientUtils {

    @Resource
    private LicenseServer licenseServer;

    public String generateRegisterCode(LicenseRegisterDto registerDto){
        HttpResponse response = HttpRequest.post(initUrl("/license/custom/register"))
                .body(JSONUtil.toJsonStr(registerDto))
                .execute();
        return response.body();
    }

    public String generateLicenseCode(String registerCode){
        HttpResponse response = HttpRequest.post(initUrl("/license/custom/license"))
                .form("registerCode", registerCode)
                .execute();
        return response.body();
    }

    public boolean customRegister(String registerCode, String licenseCode){
        HttpResponse response = HttpRequest.post(initUrl("/license/custom"))
                .form("registerCode", registerCode)
                .form("licenseCode", licenseCode)
                .execute();
        return "true".equals(response.body());
    }

    public LicenseDto licenseStatus(String customName, String ip, String sysName){
        HttpResponse response = HttpRequest.get(initUrl("/license/custom"))
                .form("customName", customName)
                .form("ip", ip)
                .form("sysName", sysName)
                .execute();
        if (response.body() == null || "".equals(response.body())) {
            return null;
        }
        return JSONUtil.parseObj(response.body()).toBean(LicenseDto.class);
    }

    public String initUrl(String apiUrl){
        return licenseServer.getIp() + ":" +
                licenseServer.getPort() + apiUrl;
    }
}
